package com.example.jpa.crud.controller;

import com.example.jpa.crud.exception.*;
import com.example.jpa.crud.model.ResourceModelSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ControllerAdvice {

    private static final Logger log = LoggerFactory.getLogger(ControllerAdvice.class);

    private final ResourceModelSupport resourceModelSupport;

    public ControllerAdvice(ResourceModelSupport resourceModelSupport) {
        this.resourceModelSupport = resourceModelSupport;
    }

    @ExceptionHandler(
            value = {
                    ResourceModelNotFoundException.class,
                    UnknownFieldException.class,
                    ExpressionException.class,
                    ParameterMissingException.class,
                    ParameterTypeConvertException.class,
                    RequestBodyMissingException.class
            }
    )
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleException(Exception e) {
        log.error("handleException", e);
        return resourceModelSupport.getResponseTemplate().err(e);
    }

}
